package com.example.springbootweb.zk;

import org.apache.zookeeper.*;

import java.io.IOException;
import java.util.concurrent.CountDownLatch;

/**
 * Create with Intellij idea
 * User:mingtian
 * Date:2018/10/10
 * Time:17:52
 */
public class Test1 {

    /**
     * zookeeper连接地址
     */
    private static final String connection = "127.0.0.1:2181";

    /**
     * session超时时间
     */
    private static final int sessionOuttime = 5000;

    /**
     * 使用java并发包 信号量技术 控制zookeeper连接成功之后，开始创建节点，否则情况下等待
     */
    private static final CountDownLatch countDownLatch = new CountDownLatch(1);

    /**
     * java语言操作zookeeper
     *
     * @param args
     * @throws IOException
     * @throws KeeperException
     * @throws InterruptedException
     */
    public static void main(String[] args) throws IOException, KeeperException, InterruptedException {
        //1.zookeeper创建了一个连接
        ZooKeeper zooKeeper = null;
        try {
            zooKeeper = new ZooKeeper(connection, sessionOuttime, new Watcher() {
                //watch监听节点是否发生变化
                public void process(WatchedEvent event) {
                    // 获取事件状态
                    Event.KeeperState keeperState = event.getState();
                    // 获取事件类型
                    Event.EventType eventType = event.getType();
                    //同步连接
                    if (Event.KeeperState.SyncConnected == keeperState) {
                        if (Event.EventType.None == eventType) {
                            countDownLatch.countDown();//调用发方法的时候 减1，如果为0的话，
                            System.out.println("zk 启动连接...");
                        }
                        if (Event.EventType.NodeCreated == eventType) {
                            System.out.println("zookeeper 事件通知");
                        }
                    }
                }
            });
            countDownLatch.await();//如果我的计数器不是为0的话  会一直等待
            String path = "/temp";
            //判断事件通知
            zooKeeper.exists(path, true);
            //2.节点类型
            //1.CreateMode.EPHEMERAL 创建一个临时节点
            //2.CreateMode.EPHEMERAL_SEQUENTIAL 如果节点发生重复的情况下，id自动自增 保证唯一性
            //3.CreateMode.PERSISTENT 持久类型 永久保存在硬盘上
            //4.CreateMode.PERSISTENT_SEQUENTIAL 持久类型 如果节点发生重复的情况下，id会自增  保证唯一性
            String nodeResult = zooKeeper.create("/test1/test5", "ming".getBytes(), ZooDefs.Ids.OPEN_ACL_UNSAFE, CreateMode.EPHEMERAL);
            System.out.println("节点名称:" + nodeResult);

        } catch (Exception e) {
            e.printStackTrace();
            System.out.println(e);
        } finally {
            if (zooKeeper != null) {
                Thread.sleep(10 * 1000);
                //关闭zookeeper连接
                zooKeeper.close();
            }
        }


    }
}
